package com.example.phoneshop.controller.admin;

import com.example.phoneshop.config.Config;
import com.example.phoneshop.entity.Goods;
import com.example.phoneshop.entity.PageBean;
import com.example.phoneshop.entity.User;
import com.example.phoneshop.service.GoodsService;
import com.example.phoneshop.service.impl.GoodsServiceImpl;
import com.example.phoneshop.tool.Check;
import com.example.phoneshop.tool.ResultJson;
import com.example.phoneshop.tool.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * @author Chen
 * @date 2018/7/816:51
 */
@SuppressWarnings("Duplicates")
@Controller
@RequestMapping(value = "admin/goods")
public class GoodsController {

    private String[] menu;
    @Autowired
    private GoodsService goodsService;

    @RequestMapping(value = {"index", "/", ""}, method = RequestMethod.GET)
    public ModelAndView index(  @RequestParam(value = "page", required = false,defaultValue = "1")int page,
                               HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        // 判断是否登录
        if (AdminOrderController.isAdminLogin(session, response)) return null;

        ModelAndView model = new ModelAndView("admin/goods/goods_info");
        // 获取导航栏的active数组
        menu = Config.getMenu();
        model.addObject("user", (User) session.getAttribute("user"));
        model.addObject("title", "商品信息");
        model.addObject("classurl", request.getContextPath() + "/admin/index");
        model.addObject("classname", "商品管理");
        menu[1] = "open active";
        menu[4] = "active";
        model.addObject("menu", menu);
        Map<String, Object> map = new HashMap<String, Object>();
        PageBean<Goods> pageMsg=goodsService.findGoodsByPage(page);
        List<Goods> goodsList = pageMsg.getList();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long t=null;
        String sd=null;
        for(Goods v:goodsList){
            t=Long.parseLong(v.getUpload_time());
            sd = sdf.format(new Date(t));
            v.setUpload_time(sd);
        }
        model.addObject("pageMsg", pageMsg);
        model.addObject("page", page);
        model.addObject("totalPage", pageMsg.getTotalPage());
        return model;
    }

    @RequestMapping(value = {"upload", "/", ""}, method = RequestMethod.GET)
    public ModelAndView upload(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        // 判断是否登录
        if (AdminOrderController.isAdminLogin(session, response)) return null;

        ModelAndView upload = new ModelAndView("admin/goods/goods_upload");
        menu = Config.getMenu();
        upload.addObject("user", (User) session.getAttribute("user"));
        upload.addObject("title", "商品上传");
        upload.addObject("classurl", request.getContextPath() + "/admin/upload");
        upload.addObject("classname", "商品管理");
        menu[1] = "open active";
        menu[2] = "active";
        upload.addObject("menu", menu);
        return upload;
    }

    @RequestMapping(value = "/addGoods", method = RequestMethod.POST)
    public @ResponseBody
    ResultJson
    addGoods(@RequestParam("name[]") String name[], @RequestParam("value[]") String[] value,@RequestParam("move[]") String[] move, HttpSession session, HttpServletResponse response) {
        // 判断是否登录
        if (AdminOrderController.isAdminLogin(session, response)) return null;
        ResultJson resultJson = new ResultJson();
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        for (String v : name) {
            map.put(v, value[i++]);
        }
        int j=0;
        map.put("upload_time", Calendar.getInstance().getTimeInMillis() + "");
        map.put("goods_id",null);
        resultJson.setText("success");
        goodsService.addGoodsByMap(map);
        for (String v : move) {
            map.put("good_show_img_path",Tool.base64Decode(move[j++]));
            goodsService.addGoodsImg(map);
        }
        return resultJson;
    }

    @RequestMapping(value = "uploadGoodsType", method = RequestMethod.GET)
    public ModelAndView uploadGoodsType(HttpServletResponse response, HttpSession session, HttpServletRequest request) {
        // 判断是否登录
        if (AdminOrderController.isAdminLogin(session, response)) return null;

        ModelAndView model = new ModelAndView("admin/goods/uploadGoodsType");
        // 获取导航栏的active数组
        menu = Config.getMenu();
        model.addObject("user", (User) session.getAttribute("user"));
        model.addObject("title", "商品类型上传");
        model.addObject("classurl", request.getContextPath() + "/admin/index");
        model.addObject("classname", "商品管理");
        menu[1] = "open active";
        menu[5] = "active";

        model.addObject("menu", menu);
        return model;
    }

    @RequestMapping(value = "uploadGoodsTypeHandle", method = RequestMethod.POST)
    public @ResponseBody
    ResultJson uploadGoodsTypeHandle(HttpSession session, HttpServletResponse response, @RequestParam("name") String name) {
        // 判断是否登录
        if (AdminOrderController.isAdminLogin(session, response)) return null;
        ResultJson resultJson = new ResultJson();
        int result = 0;
        try {
            result = goodsService.insertGoodType(name);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(result == 1){
            resultJson.setText("ok");
        }else{
            resultJson.setText("上传失败，请稍候再试");
        }
        return resultJson;
    }

    @RequestMapping(value = "uploadImageHandle", method = RequestMethod.POST)
    public @ResponseBody ResultJson uploadImageHandle(HttpSession session, HttpServletResponse response, HttpServletRequest request, @RequestParam("file[]") MultipartFile[] files){
        // 判断是否登录
        if (!Check.checkAdminLogin(session)) {
            try {
                response.sendRedirect("/admin/login");
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ResultJson resultJson = new ResultJson();
        ArrayList<String> fileNameArr = new ArrayList<String>();
        ArrayList<String> fileType = Config.getAllowImageType();
        ArrayList<String> fileTypeArr = new ArrayList<String>();
        String fileName;
        for (MultipartFile file : files) {
            fileName = file.getOriginalFilename();
            fileTypeArr.add(fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null);
            fileNameArr.add(fileName);
        }
        // 判断图片类型是否合法
        for (String v : fileTypeArr) {
            if (!fileType.contains(v)) {
                resultJson.setText("图片类型不合法");
                return resultJson;
            }
        }
        int len = fileNameArr.size();
        boolean flag = true;
        // 新创建文件名
        String fileNewName[] = new String[len];
        String fileNewNameReal[] = new String[len];
        // 判断上传文件夹是否存在，不存在则创建
        String dir = request.getSession().getServletContext().getRealPath("/") + "uploads/";
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        // 遍历产生新的文件名同时进行保存和返回
        for (int i = 0; i < len; i++) {
            fileNewName[i] = Calendar.getInstance().getTimeInMillis() + "" + (int) (Math.random() * 100) + "." + fileTypeArr.get(i);
            fileNewNameReal[i] = dir + fileNewName[i];
            // 移动文件到指定上传目录
            try {
                files[i].transferTo(new File(fileNewNameReal[i]));
            } catch (IOException e) {
                flag = false;
                e.printStackTrace();
            }
        }
        if (!flag) {
            resultJson.setText("图片上传出错，未知错误");
        } else {

            resultJson.setText(request.getContextPath() + "/uploads/" + fileNewName[0]);
            resultJson.setId(fileNewNameReal[0]);
            resultJson.setReply("1");
        }
        return resultJson;
    }
    @RequestMapping(value={"sell", "/", ""},method = GET)
    public ModelAndView onSell(@RequestParam(value = "page", required = false,defaultValue = "1")int page,HttpServletResponse response, HttpSession session, HttpServletRequest request){
        // 判断是否登录
        if (AdminOrderController.isAdminLogin(session, response)) return null;
        ModelAndView model = new ModelAndView("admin/goods/goods_sell");
        // 获取导航栏的active数组
        menu = Config.getMenu();
        model.addObject("user", (User) session.getAttribute("user"));
        model.addObject("title", "商品上架");
        model.addObject("classurl", request.getContextPath() + "/admin/index");
        model.addObject("classname", "商品管理");
        menu[1] = "open active";
        menu[3] = "active";
        model.addObject("menu", menu);
        Map<String, Object> map = new HashMap<String, Object>();
        PageBean<Goods> pageMsg=goodsService.findGoodsByPage(page);
        List<Goods> goodsList = pageMsg.getList();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long t=null;
        String sd=null;
        for(Goods v:goodsList){
            t=Long.parseLong(v.getUpload_time());
            sd = sdf.format(new Date(t));
            v.setUpload_time(sd);
        }
        model.addObject("pageMsg", pageMsg);
        model.addObject("page", page);
        model.addObject("totalPage", pageMsg.getTotalPage());
        return model;
    }
    @RequestMapping(value = "/onSell", method = RequestMethod.POST)
    public @ResponseBody
    ResultJson
    onSell(@RequestParam("id") int id, HttpSession session, HttpServletResponse response) {
        // 判断是否登录
        if (AdminOrderController.isAdminLogin(session, response)) return null;
        ResultJson resultJson = new ResultJson();
        Goods goods = new Goods();
        goods.setId(id);
        goods.setIs_on_sell(1);
        goodsService.updateGoods(goods);
        resultJson.setText("success");
        return resultJson;
    }
    @RequestMapping(value = "/notSell", method = RequestMethod.POST)
    public @ResponseBody
    ResultJson
    notSell(@RequestParam("id") int id, HttpSession session, HttpServletResponse response) {
        // 判断是否登录
        if (AdminOrderController.isAdminLogin(session, response)) return null;
        ResultJson resultJson = new ResultJson();
        Goods goods = new Goods();
        goods.setId(id);
        goods.setIs_on_sell(0);
        goodsService.updateGoods(goods);
        resultJson.setText("success");
        return resultJson;
    }

}











